<?php

class App_Model_DbTable_Tag_Recommend_Sort extends Ext_Db_Table  
{  
	/** Table name */  
    protected $_name = 'tag_recommend_sort';
    
    private static $_recommendSortRow = array();

	public function getRow($sortId)
	{
		if(!$sortId)
		{
			return "";
		}
		
		if(isset(self::$_recommendSortRow[$sortId]))
		{
			return self::$_recommendSortRow[$sortId];
		}
		
		$db = $this->getAdapter();
		$safe = $db->quoteInto(" id = ? ", $sortId);
		$row = $this->fetchRow($safe);
		if (!$row) {
			return "";
		}
		$_recommendSortRow = $row->toArray();

		self::$_recommendSortRow[$sortId] = $_recommendSortRow;
		
		return $_recommendSortRow;
	}
	
	public function getAll()
	{
		$db = $this->getAdapter();
		$select = $db->select();
		$select
			->from($this->_name, "*")
			->order('sequence ASC')
			;
		$list = $db->fetchAll($select);
		return $list;
	}
	
	public function getMaxSequence()
	{
		$db = $this->getAdapter();
		$select = $db->select();
		$select
			->from($this->_name, "MAX(sequence)")
			;
		$order = $db->fetchOne($select);
		return $order;
	}
	
	public function del($id)
	{
		$db = $this->getAdapter();
		$safe = $db->quoteInto(" id = ? ", $id);
		$rows_affected = $this->delete($safe);
		
		return $rows_affected;
	}
		   
	public function addNew($inputArray)
	{
		$sql_data_array = array();
		if(array_key_exists('sortName', $inputArray)) $sql_data_array['sortName'] = $inputArray['sortName'];
		if(array_key_exists('sequence', $inputArray)) $sql_data_array['sequence'] = $inputArray['sequence'];
		
		try {
			$rows_affected = $this->insert($sql_data_array);
			$last_insert_id = $this->getAdapter()->lastInsertId();
		}catch (Exception $e){
			trigger_error($e->getMessage(), E_USER_WARNING);
		}
		return $last_insert_id;
	}
	
	public function addOld($inputArray, $sortId)
	{
		$sql_data_array = array();
		if(array_key_exists('sortName', $inputArray)) $sql_data_array['sortName'] = $inputArray['sortName'];
		if(array_key_exists('sequence', $inputArray)) $sql_data_array['sequence'] = $inputArray['sequence'];
		if(!$sql_data_array)
		{
			return "";
		}
		
		try {
			$db = $this->getAdapter();
			$where = $db->quoteInto(" id = ? ", $sortId);
			$rows_affected = $this->update($sql_data_array, $where);
			if($rows_affected)
			{
				unset(self::$_recommendSortRow[$sortId]);
			}
		}catch (Exception $e){
			trigger_error($e->getMessage(), E_USER_WARNING);
		}
	}
}